package com.hai.mall.product.service.impl;

import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.stream.Collector;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hai.common.utils.PageUtils;
import com.hai.common.utils.Query;

import com.hai.mall.product.dao.CategoryDao;
import com.hai.mall.product.entity.CategoryEntity;
import com.hai.mall.product.service.CategoryService;


@Service("categoryService")
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, CategoryEntity> implements CategoryService {

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<CategoryEntity> page = this.page(
                new Query<CategoryEntity>().getPage(params),
                new QueryWrapper<CategoryEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public List<CategoryEntity> listWithTree() {
        List<CategoryEntity> categoryEntities = baseMapper.selectList(null);

        List<CategoryEntity> level1Meun = categoryEntities.stream()
                .map((menu)-> {
                    menu.setChildren(getChildrens(menu,categoryEntities));
                    return menu;
                })
                .sorted((meun1,meun2)->{
                    return (meun1.getSort()==null?0:meun1.getSort())-(meun2.getSort()==null?0:meun2.getSort());
                })
                .filter(categoryEntity -> categoryEntity.getParentCid()==0).collect(Collectors.toList());

        return level1Meun;
    }

    @Override
    public void removeMeunByIds(List<Long> asList) {

    }

    public List<CategoryEntity> getChildrens(CategoryEntity root, List<CategoryEntity> all) {

        List<CategoryEntity> chirldren = all.stream()
                .filter(categoryEntity -> {
                   return categoryEntity.getParentCid() == root.getCatId();
                })
                .map((categoryEntity)-> {
                    categoryEntity.setChildren(getChildrens(categoryEntity,all));
                    return categoryEntity;
                })
                .sorted((meun1,meun2)->{
                    return (meun1.getSort()==null?0:meun1.getSort())-(meun2.getSort()==null?0:meun2.getSort());
                })
                .collect(Collectors.toList());

        return chirldren;
    }

}